package testdomainsupermarket;

import java.util.HashMap;
import java.util.Iterator;

import conditionsAPI.ConditionDuplicatedException;
import conditionsAPI.SimpleDomainCondition;

public class SodasSameBrandCondition extends SimpleDomainCondition{

	private HashMap<String,Integer> sodaCounts;
	private int expectedNumSodas;
	
	public SodasSameBrandCondition(String id)
			throws ConditionDuplicatedException {
		super(id);
		this.sodaCounts = new HashMap<String,Integer>();
		this.expectedNumSodas = 0; 
	}
	
	public void setExpectedNumSodas(int expectedNumSodas){
		this.expectedNumSodas = expectedNumSodas;
	}

	private void addSodaToSodaCount(LineItem lineItem){
		String key = lineItem.getBrandName().toString();
		if (this.sodaCounts.containsKey(key)){
			int sodaCount = this.sodaCounts.get(key).intValue();
			sodaCount++;
			this.sodaCounts.put(key,sodaCount);
		}
		else{
			this.sodaCounts.put(key, new Integer(1));
		}
	}
	
	private boolean hasExpectedSodasSameBrand(){
		Iterator<Integer> sodaCountsIterator = this.sodaCounts.values().iterator();
		while (sodaCountsIterator.hasNext()){
			int sodaCount = sodaCountsIterator.next().intValue();
			if (sodaCount == this.expectedNumSodas) return true;
		}
		return false;
	}
	
	@Override
	public boolean checkConditionState(Object domainObject) {
		LineItem lineItem = (LineItem) domainObject;
		if (lineItem.getCategory().equals(LineItem.Categories.SODA)){
			this.addSodaToSodaCount(lineItem);
		}
		return hasExpectedSodasSameBrand();
	}
	
	protected boolean resetToInitialState(){
		this.sodaCounts.clear();
		return false;
	}

}
